/**
 * step 1 受眾管理、生成用户定位
 */
define(['../../common/service', './createAdUtils', '../../common/copybox', '../audienceManager/userAudienceKit'],
    function (http,adUtils,CB,userAudienceKit) {
        var Step1 = {
            self : this,
            actions : [{'id' : 'ViewContent', 'text': 'Viewed'},{'id' : 'AddToCart', 'text': 'Added to cart'},{'id' : 'Purchase', 'text': 'Purchased'}],
            retention_seconds_unit : 24 * 60 * 60,
            _publishParamCache :{},
            init: function () {
                var _this = this;
                _this.render();
                _this.bindEvent();
            },
            bindEvent : function(){
                var _this = this;
                 _this.generateAudienceEvent();
                 _this.saveAudienceEvent();
            },
            saveAudienceEvent : function(){
                var _this = this;
                $(".btn-save-audience", "#edit-audience-modal").off("click").on("click", function(){
                    if ($(this).hasClass("disabled")){
                        return false;
                    }

                    var _name = $.trim($('input[name="audience-name"]', "#edit-audience-modal").val());
                    if ('' == _name){
                        Kit.warning5($('div.fmp-article'), 600, $('input[name="audience-name"]', "#edit-audience-modal"));
                        Kit.alert2( I18N.getText('audienceManager', 'enterAudienceR'));
                        return false;
                    }

                    $(this).addClass("disabled");
                    var param = {
                        weFeedId : adUtils.publishParamCache.weFeedId,
                        fbAccountId :  adUtils.publishParamCache.fbAccountId,
                        productCatalogId : $("div.ndp-drop-wrapper[name=productSet-drop]").drop("data").fb_ids[0].catalog_id,
                        productSetId : adUtils.publishParamCache.productSetId,
                        name : _name,
                        localTargeting : _this.eidtAudineceCache.localTargeting,
                        fbTargeting : _this.eidtAudineceCache.fbTargeting,
                        potentialUser : _this.eidtAudineceCache.potentialUser
                    }
                    http.work('/useraudiences/save',param,'POST').then(function(res){
                        if (res.flag == "success"){
                            param.id = res.data;
                            param.localTargeting = JSON.stringify(param.localTargeting);
                            param.fbTargeting = JSON.stringify(param.fbTargeting);
                            _this.audienceTemplates.unshift(param);
                            var appsData = [{id : -1, text : I18N.getText("createAd","newAudience")}];
                            $.each(_this.audienceTemplates, function (i, obj) {
                                //处理渲染的数据
                                obj.text = obj.name;
                                appsData.push(obj);
                            });
                            $.extend(adUtils.audienceCache, _this.eidtAudineceCache);
                            _this.renderAudienceTemplates(appsData, appsData[1]);

                            //如果保存成功
                            $("#edit-audience-modal").modal("hide");
                        } else {
                            $(".btn-save-audience", "#edit-audience-modal").removeClass("disabled");
                            if (res.errorCode == "60136"){
                                Kit.warning5($('div.fmp-article'), 600, $('input[name="audience-name"]', "#edit-audience-modal"));
                            }
                            Kit.alert2(res.msg || I18N.getText('audienceManager', 'createAudienceFail'));
                        }
                    })
                })
            },
            generateAudienceEvent : function(){
                var _this = this;
                $(".btn-generate-audience", "#audience").off("click").on("click", function(){
                    if ($(this).hasClass("disabled")){
                        return false;
                    }
                    $(this).addClass("disabled");
                    var _container = $(".new-audience")
                    $(".btn-save-audience", _container).addClass("disabled");
                    adUtils.audienceCache = {};
                    _this.generateAudience(_container, adUtils.audienceCache);
                })

                $(".btn-generate-audience", "#edit-audience-modal").off("click").on("click", function(){
                    if ($(this).hasClass("disabled")){
                        return false;
                    }
                    _this.eidtAudineceCache = {};
                    $(this).addClass("disabled");
                    var _container = $("#edit-audience-modal")
                    $(".btn-save-audience", _container).addClass("disabled");
                    _this.generateAudience(_container, _this.eidtAudineceCache);
                })
            },
            generateAudience : function(_container, _cache){
                var _this = this;
                $(".audience-result", _container).empty();
                //先校验用户条件
                var targeting_spec = {};
                if (!_this.verifyAudience(targeting_spec, _container)){
                    $(".btn-generate-audience", _container).removeClass("disabled");
                    return false;
                }

                //年龄
                targeting_spec.age_min = $("div.ndp-drop-wrapper[name=min-age]", _container).data("val");
                targeting_spec.age_max = $("div.ndp-drop-wrapper[name=max-age]", _container).data("val");

                //性别
                var _gender = $('input[name="gender"]:checked', _container).val()
                if ('0' != _gender){
                    targeting_spec.genders = [_gender];
                }

                ////TODO 此处只是验证
                //targeting_spec.flexible_spec = [{"interested_in":["3"]}];
                _cache.fbTargeting = targeting_spec;
                _cache.localTargeting = _this.buildLocalTargeting(_container)
                if ($('input[name="cross-selling"]').prop("checked")){
                    _cache.produceSetId = $('div.ndp-drop-wrapper[name="audience-product-set-drop"]').data("val");
                }

                var par = {
                    targeting_spec : targeting_spec,
                    account_id : adUtils.publishParamCache.fbAccountId
                };
                http.work('/useraudiences/previewSimpleUserAudience', par, 'POST').then(function(res){
                    if(res.flag == 'success') {
                        setTimeout(function(){
                            _this.keepCalling(res.data.userAudienceCacheId, _container, _cache);
                        },200)
                    } else {
                        _this.useraudienceError(res.msg, _container, _cache);
                    }
                },function(err){
                    _this.useraudienceError(I18N.getText('management', 'generateAudienceFailed'), _container, _cache);
                })
            },
            buildLocalTargeting : function(_container){
                var localTargeting = {};
                //规则
                var rules = [];
                var ruleEs = $(".rule-item", _container).find(".range-c");
                $.each(ruleEs, function(i, ruleE) {
                    var actions = $(ruleE).find(".actions").select2("data");
                    if (actions.length) {
                        var _min = $(ruleE).find('input[name="min"]').val()
                        var _max = $(ruleE).find('input[name="max"]').val()
                        rules.push({
                            min : _min,
                            max : _max,
                            actions : actions
                        })
                    }
                });
                localTargeting.rules =  rules;

                //版位
                var page_types = [];
                $.each($('input[name="page-type"]:checked', _container), function(i, page_type){
                    page_types.push($(page_type).val());
                })
                localTargeting.page_types = page_types;
                //自定义受众
                localTargeting.customAudiences = $(".customaudience", _container).select2("data");
                //地区
                var selectLocations = $(".location-select2", _container).select2("data");
                localTargeting.location = {
                    locationType : $("div.ndp-drop-wrapper[name=location_types]", _container).data("val"),
                    locations : selectLocations
                }
                //年龄
                localTargeting.age = {
                    age_min : $("div.ndp-drop-wrapper[name=min-age]", _container).data("val"),
                    age_max : $("div.ndp-drop-wrapper[name=max-age]", _container).data("val"),
                }

                //性别
                localTargeting.gender = $('input[name="gender"]:checked',  _container).val();
                return localTargeting;
            },
            verifyAudience : function(_targeting_spec, _container){
                var _this = this;
                if (!verifyRules(_targeting_spec, _container)){
                    return false;
                }

                //版位
                if (!verifyPageType(_targeting_spec, _container)){
                    return false;
                }

                buildCustomAudiences(_targeting_spec, _container);

                if (!verifyLocations(_targeting_spec, _container)){
                    return false;
                }

                function verifyPageType(_targeting_spec, _container){
                    var page_types = [];
                    $.each($('input[name="page-type"]:checked', _container), function(i, page_type){
                        page_types.push($(page_type).val());
                    })

                    if (page_types.length == 0){
                        Kit.alert2(I18N.getText('audienceManager', 'selectPlacement'));
                        return false;
                    }

                    _targeting_spec.page_types = page_types;
                    return true;
                }

                function verifyRules(_targeting_spec){
                    var flag = true;
                    var rules = $(".rule-item", _container).find(".range-c");
                    var inclusions = [];
                    var exclusions = [];

                    $.each(rules, function(i, _rule){
                        var actions = $(_rule).find(".actions").select2("data");
                        if (actions.length){
                            var _minE = $(_rule).find('input[name="min"]');
                            var _minv = _minE.val();
                            if (_minv == ''){
                                _minE.addClass("form-input-warning").addClass("can-clear");
                                Kit.alert2(I18N.getText('audienceManager', 'minReminder'));
                                flag = false;
                                return false;
                            }
                            var _min_retention_seconds = Number(_minv) * _this.retention_seconds_unit;

                            var _maxE = $(_rule).find('input[name="max"]');
                            var _maxv = _maxE.val();
                            var _max_retention_seconds = _maxv == '' ? 0 :( Number(_maxv) * _this.retention_seconds_unit);

                            if (Number(_minv) < 1 || Number(_minv) > 180){
                                _minE.addClass("form-input-warning").addClass("can-clear");
                                $(_rule).find(".i-range-r").addClass("can-clear-r").removeClass("hide").html(I18N.getText('audienceManager', 'dataRangeR'))
                                flag = false;
                                return false;
                            }

                            if (_maxv != '' && (Number(_maxv) < 1 || Number(_maxv) > 180)){
                                _maxE.addClass("form-input-warning").addClass("can-clear");
                                $(_rule).find(".i-range-r").addClass("can-clear-r").removeClass("hide").html(I18N.getText('audienceManager', 'dataRangeR'))
                                flag = false;
                                return false;
                            }

                            if (_maxv != '' && _min_retention_seconds >= _max_retention_seconds){
                                $(_rule).find(".i-range-r").addClass("can-clear-r").removeClass("hide").html(I18N.getText('audienceManager', 'nearFarR'))
                                flag = false;
                                return false;
                            }

                            $.each(actions, function(i, _action_o){
                                if (_action_o.isClude == 1 || _action_o.isClude == '1'){
                                    //包括
                                    if (_max_retention_seconds == 0){
                                        inclusions.push({
                                            "retention_seconds" : _min_retention_seconds,
                                            "rule" : {
                                                "event" : {
                                                    "eq" : _action_o.id
                                                }
                                            }})
                                    } else {
                                        inclusions.push({
                                            "retention_seconds" : _max_retention_seconds,
                                            "rule" : {
                                                "event" : {
                                                    "eq" : _action_o.id
                                                }
                                            }});

                                        exclusions.push({
                                            "retention_seconds" : _min_retention_seconds,
                                            "rule" : {
                                                "event" : {
                                                    "eq" : _action_o.id
                                                }
                                            }})
                                    }
                                } else {
                                    exclusions.push({
                                        "retention_seconds" : _max_retention_seconds == 0 ? _min_retention_seconds : _max_retention_seconds,
                                        "rule" : {
                                            "event" : {
                                                "eq" : _action_o.id
                                            }
                                        }})
                                }
                            })
                        }
                    });

                    if (!flag){
                        return false;
                    }

                    if (inclusions.length == 0){
                        Kit.alert2(I18N.getText('audienceManager', 'actionReminder'));
                        flag = false;
                        return false;
                    }

                    var product_audience_specs = {
                        inclusions : inclusions
                    }

                    if ($('input[name="cross-selling"]').prop("checked")){
                        product_audience_specs.product_set_id = $("div.ndp-drop-wrapper[name=audience-product-set-drop]").drop("data").fb_ids[0].fb_productset_id;
                    } else {
                        product_audience_specs.product_set_id = $("div.ndp-drop-wrapper[name=productSet-drop]").drop("data").fb_ids[0].fb_productset_id;
                    }

                    if (exclusions.length){
                        product_audience_specs.exclusions = exclusions;
                    }

                    _targeting_spec.product_audience_specs = [product_audience_specs];

                    return flag;
                }

                function verifyLocations(_targeting_spec, _container){
                    var  locationResults = userAudienceKit.buildLocation({"locationArea" : $(".location-select2", _container)} )

                    var geo_locations = locationResults.geo_locations;
                    var excluded_geo_locations = locationResults.excluded_geo_locations;
                    if (!geo_locations){
                        Kit.alert2(I18N.getText('audienceManager', 'oneLocation'));
                        return false;
                    }

                    if (geo_locations){
                        _targeting_spec.geo_locations = geo_locations;
                        //地区类型
                        var _locationTypes = $("div.ndp-drop-wrapper[name=location_types]", _container).data("val");
                        if (_locationTypes == 1){
                            //这个地区所有人
                            geo_locations.location_types = ["home","recent"];
                        } else if (_locationTypes == 2){
                            //在这里居住的用户
                            geo_locations.location_types = ["home"];
                        } else if (_locationTypes == 3){
                            //最近到过这里的用户
                            geo_locations.location_types = ["recent"];
                        } else {
                            //在这里旅游的用户
                            geo_locations.location_types = ["travel_in"];
                        }

                    }

                    if (excluded_geo_locations){
                        _targeting_spec.excluded_geo_locations = excluded_geo_locations;
                    }

                    return true;
                }

                function buildCustomAudiences(_targeting_spec, _container){
                    //受众
                    var _customAudiences = $(".customaudience", _container).select2("data");
                    var custom_audiences = [];
                    var excluded_custom_audiences = [];
                    if (_customAudiences && _customAudiences.length > 0){
                        $.each(_customAudiences, function(i, _customAudience){
                            if (_customAudience.isClude && (_customAudience.isClude == "1" || _customAudience.isClude == 1)){
                                custom_audiences.push({id : _customAudience.id, name : _customAudience.name});
                            } else {
                                excluded_custom_audiences.push({id : _customAudience.id, name : _customAudience.name});
                            }
                        });
                    }

                    if (custom_audiences && custom_audiences.length){
                        _targeting_spec.custom_audiences = custom_audiences;
                    }

                    if (excluded_custom_audiences && excluded_custom_audiences.length > 0){
                        _targeting_spec.excluded_custom_audiences = excluded_custom_audiences;
                    }
                }

                return true;
            },

            render : function(){
                var _this = this;
                /**********  step 1 推广目标-受众 ***********/
                _this.audience_init();
                //编辑受众
                _this.initEditAudienceModal();
            },
            initEditAudienceModal : function(){
                var _this = this;
                var _editAudience = $("#edit-audience-modal");
                _editAudience.modal({
                    backdrop: 'static',
                    keyboard: false,
                    show:false
                });

                _editAudience.on('show.bs.modal', function (e) {
                    $(".new-audience-c").empty();
                    _editAudience.find(".edit-audience-c").html(_.template($('#t-new-audience').text())());
                    _editAudience.find('input[name="audience-name"]').val('')
                    _this.renderAudience(_editAudience);
                    //回填受众数据
                    _this.fillAudience(_editAudience);

                    $(".btn-save-audience", _editAudience).addClass("disabled");
                    $(".audience-result", _editAudience).empty();
                });

                $(".btn-audience-edit").off("click").on("click", function(e){
                    _editAudience.modal("show");
                })
            },
            fillAudience : function(_container){
                var _this = this;
                var _localTargeting =  JSON.parse(_this.audience.localTargeting);

                //回填规则
                if (_localTargeting.rules && _localTargeting.rules.length) {
                    $.each(_localTargeting.rules, function(i, _rule){
                        if (i != 0){
                            _container.find(".btn-plus").trigger('click');
                        }

                        var _cbox = _container.find('.cbox','.rule-item ').eq(i);
                        _cbox.find('input[name="min"]').val(_rule.min || '');
                        _cbox.find('input[name="max"]').val(_rule.max || '');
                        //行为
                        if (_rule.actions || _rule.actions.length){
                            var _ce = _cbox.find('.actions');
                            $.each(_rule.actions, function(i, _action){
                                _cbox.find('.actions').find("option[value='" +  _action.id  +  "']").remove();

                                //选了某一个后其他的不能选
                                $.each($(".rule-item", _container).find(".actions"), function(i, _e){
                                    if (_ce[0] != this){
                                        $(_e).find('option[value="' + _action.id  + '"]').remove();
                                    }
                                })
                            })

                            _cbox.find('.actions').select2("data", _rule.actions);

                        }
                    })

                    _this.canAdd(_container);
                }

                //回填版位
                if (_localTargeting.page_types && _localTargeting.page_types.length){
                    $.each(_localTargeting.page_types, function(i, _page_type){
                        _container.find('input[value="' + _page_type +  '"]').prop("checked", "checked");
                    })
                }

                //回填受众
                if (_localTargeting.customAudiences && _localTargeting.customAudiences.length){
                    var _cs = _container.find(".customaudience");
                    $.each(_localTargeting.customAudiences, function(i, _cv){
                        _cs.find("option[value='" +  _cv.id  +  "']").remove();
                    })

                    _cs.select2("data", _localTargeting.customAudiences);
                }

                //回填地区
                if (_localTargeting.location){
                    var _locationType = _localTargeting.location.locationType;
                    var _locationTypesE = _container.find("div.ndp-drop-wrapper[name=location_types]");
                    if (_locationType == 1 ){
                        _locationTypesE.drop('val', {name : I18N.getText('createAd', 'peopleAllHere'), val : '1'});
                    } else {
                        if (_locationType == 2){
                            _locationTypesE.drop('val', {name : I18N.getText('createAd', 'peopleLiveInHere'), val : '2'});
                        }

                        if (_locationType == 3){
                            _locationTypesE.drop('val', {name : I18N.getText('createAd', 'peopleRecentlyHere'), val : '3'});
                        }

                        if (_locationType == 4){
                            _locationTypesE.drop('val', {name : I18N.getText('createAd', 'peopleTravelingHere'), val : '4'});
                        }
                    }

                    _container.find(".location-select2").select2("data", _localTargeting.location.locations);
                }

                //回填年龄
                if (_localTargeting.age){
                    _container.find("div.ndp-drop-wrapper[name=min-age]").drop('val',
                        {name : _localTargeting.age.age_min, val : _localTargeting.age.age_min});

                    _container.find("div.ndp-drop-wrapper[name=max-age]").drop('val',
                        {name : _localTargeting.age.age_max, val : _localTargeting.age.age_max});
                }

                //回填性别
                if (_localTargeting.gender){
                    _container.find('input[name="gender"][value="' + _localTargeting.gender + '"]').prop("checked", "checked");
                }

                //名称
                //_container.find('input[name="audience-name"]').val(_this.audience.name || '');

            },
            canAdd : function (_container){
                var _this = this;
                var selectedNum = 0;
                var actionsGroups = _container.find(".rule-item").find(".actions");
                var _num;
                $.each(actionsGroups, function(i, _actitons){
                    _num = $(_actitons).select2("data").length;
                    if (_num == 0){
                        _num += 1;
                    }
                    selectedNum += _num ;
                })
                if ((_this.actions.length - selectedNum) < 1){
                    _container.find('.btn-plus').addClass("hide");
                } else {
                    _container.find('.btn-plus').removeClass("hide");
                }
            },
            renderAudience: function(_container, selectedProductSet){
                var _this = this;
                //规则
                _this.renderAudienceRule(_container, selectedProductSet);

                //版位
                _this.renderPageType(_container);

                //自定义受众
                _this.renderCustomAudiences(_container);

                //地区
                _this.renderLocation(_container);

                //初始化年龄
                userAudienceKit.initAge({container: _container});
            },
            renderCustomAudiences : function(_container){
                var _this = this;
                //初始化自定义受众
                $("div.ndp-drop-wrapper[name=customaudience-include-drop]", _container).empty().drop({
                    caret:"glyphicon-menu-right",
                    data:[{name : I18N.getText('management', 'include'), val : '1'},{name :I18N.getText('management', 'exclude'), val :'0'}],
                    name:"customaudience"//为了方便serialize 建议设置name 属性
                }).val({name : I18N.getText('management', 'include'), val : '1'});


                $(".customaudience", _container).empty().select2({
                    data: _this.customAudiences,
                    placeholder: I18N.getText('management', 'chooseCustomAudience'),
                    multiple: true,
                    allowClear: false,
                    width: '100%',
                    templateSelection : function(_customAudience){
                        return _customAudience.name  + '[' + (_customAudience.isClude == 1  || _customAudience.isClude == "1" ? I18N.getText('management', 'include') : I18N.getText('management', 'exclude'))+ ']';
                    }
                }).off("select2:unselect").on("select2:unselect",function(e){
                    //_this.user_localization();
                }).off("select2:select").on("select2:select",function(e){
                    var selects = $(".customaudience", _container).select2("data");
                    var o = e.params.data
                    var index = Kit.keyIn(selects, o.id, "id")
                    if (index > -1) {
                        selects[index]["isClude"] = $("div.ndp-drop-wrapper[name=customaudience-include-drop]", _container).data("val");
                        $(".customaudience", _container).select2("data", selects);
                    }
                });
            },
            renderLocation: function (_container) {
                var _this = this;
                //地区
                $("div.ndp-drop-wrapper[name=location_types]", _container).empty().drop({
                    data: [{
                        name: I18N.getText('createAd', 'peopleAllHere'),
                        val: '1'
                    }, {name: I18N.getText('createAd', 'peopleLiveInHere'), val: '2'},
                        {
                            name: I18N.getText('createAd', 'peopleRecentlyHere'),
                            val: '3'
                        }, {name: I18N.getText('createAd', 'peopleTravelingHere'), val: '4'}],
                    caret: "glyphicon-menu-right"
                }).off("ITEM_CHANGE").on("ITEM_CHANGE", function (e) {
                }).val({name: I18N.getText('createAd', 'peopleAllHere'), val: '1'})

                var _isClude = 1;
                $("div.ndp-drop-wrapper[name=location-clude]", _container).empty().drop({
                    data: [{
                        name: I18N.getText('audienceManager', 'include'),
                        val: '1'
                    }, {name: I18N.getText('audienceManager', 'exclude'), val: '0'}],
                    caret: "glyphicon-menu-right"
                }).off("ITEM_CLICK").on("ITEM_CLICK", function (e) {
                    _isClude = e.originalEvent.data.val;
                }).val({name: I18N.getText('audienceManager', 'include'), val: '1'})

                var _cType = 'country';
                $("div.ndp-drop-wrapper[name=location-type]", _container).empty().drop({
                    data: [{
                        name: I18N.getText('audienceManager', 'country'),
                        val: 'country'
                    }, {name: I18N.getText('audienceManager', 'all'), val: 'all'}],
                    caret: "glyphicon-menu-right"
                }).off("ITEM_CLICK").on("ITEM_CLICK", function (e) {
                    _cType = e.originalEvent.data.val;
                }).val({name: I18N.getText('audienceManager', 'country'), val: 'country'})

                userAudienceKit.initLocation({
                    locationArea: $(".location-area", _container),
                    changeCallBack: function () {
                        //_this.countLocation();
                    }
                });
            },
            renderPageType : function(_container){
                _container.off("click",'input[name="page-type"]').on("click",'input[name="page-type"]', function(){
                    //移动应用受众网络版位依赖于移动版动态消息版位
                    if ($(this).val() == 'mobilefeed' && !$(this).prop('checked')){
                        $('input[name="page-type"][value="mobileexternal"]', _container).attr("checked",false);
                        $('input[name="page-type"][value="mobileexternal"]', _container).prop("checked",false);
                    }

                    if ($(this).val() == 'mobileexternal' && $(this).prop('checked')){
                        $('input[name="page-type"][value="mobilefeed"]', _container).attr("checked",true);
                        $('input[name="page-type"][value="mobilefeed"]', _container).prop("checked",true);
                    }
                })
            },
             renderAudienceRule : function(_container){
                    var _this = this;

                    var _html = '<div class="range-c cbox">' +
                        '<div>' +
                        '<label class="s-item-title">' + I18N.getText('audienceManager', 'lastDays') + '</label>' +
                        '<div class="s-item-content">' +
                        '<input class="i-range form-input" name="min" style="margin-right:10px"/> '
                        +  I18N.getText('audienceManager', 'to')
                        + ' <input class="i-range form-input" name="max" style="margin-left:10px;margin-right:10px"/> ' + I18N.getText('audienceManager', 'days') +
                        '<span class="warning-r i-range-r" for="i-range"></span>'+
                        '</div>' +
                        '</div>' +
                        '<div class="action-c">' +
                        '<div class="ndp-drop-wrapper action-i" name="action-i"></div>' +
                        '<div class="action-s">' +
                        '<select class="actions" style="width:100%"></select>' +
                        '</div>' +
                        '</div>' +
                        '<a href="javascript:void(0);" cb-del="" class="close closeBtn" style="display: block;">×</a>' +
                        '</div>';
                    var cb = new CB.CopyBox(_container.find('.rule-item'), {
                        box: _html
                        ,perInit: function($box) {
                            //规则
                            $box.find("div.ndp-drop-wrapper[name=action-i]").empty().drop({
                                data:[{name : I18N.getText('audienceManager', 'include'), val : '1'},{name :I18N.getText('audienceManager', 'exclude'), val :'0'}],
                                caret:"glyphicon-menu-right"
                            }).val({name : I18N.getText('audienceManager', 'include'), val : '1'});

                            //日期只能输整数
                            $box.find('.i-range').numeral({'scale': 0});
                            $box.find('.i-range').off("input").on("input", function(){
                                var _v = $(this).val();
                                if (_v != '' && (Number(_v) < 1 || Number(_v) > 180)){
                                    $(this).addClass("form-input-warning");
                                    $box.find(".i-range-r").removeClass("hide").html(I18N.getText('audienceManager', 'dataRangeR'))
                                    return false;
                                }

                                var _min = $box.find('input[name="min"]').val();
                                var _max = $box.find('input[name="max"]').val();
                                if (_max != '' && Number(_min) >= Number(_max)){
                                    $($box).addClass("form-input-warning");
                                    $box.find(".i-range-r").removeClass("hide").html(I18N.getText('audienceManager', 'nearFarR'))
                                    return false;
                                }

                                $box.find(".i-range-r").addClass("hide");
                                $(this).removeClass("form-input-warning");
                                $($box).removeClass("form-input-warning");
                            });

                            var _ce = $box.find(".actions");

                            $box.find(".actions").empty().select2({
                                multiple: true,
                                placeholder:I18N.getText('audienceManager', 'selectActionR'),
                                data : _this.actions,
                                templateSelection : function(_actionI){
                                    var _text = _actionI.text;
                                    return _text  + '[' + (_actionI.isClude == 1 || _actionI.isClude == '1' ? I18N.getText('audienceManager', 'include') :I18N.getText('audienceManager', 'exclude'))+ ']';
                                }
                            }).off("select2:select").on("select2:select", function(e){
                                var o = e.params.data;
                                //选了某一个后其他的不能选
                                $.each($(".rule-item", _container).find(".actions"), function(i, _e){
                                    if (_ce[0] != this){
                                        $(_e).find('option[value="' + o.id  + '"]').remove();
                                    }
                                })
                                canAdd();

                                var selects = $(_ce).select2("data");
                                var o = e.params.data
                                var index = Kit.keyIn(selects, o.id, "id")
                                if (index > -1) {
                                    selects[index]["isClude"] = $box.find("div.ndp-drop-wrapper[name=action-i]").data('val');
                                    $(_ce).select2("data", selects);
                                }
                            }).off("select2:unselect").on("select2:unselect", function(e){
                                var o = e.params.data;
                                //删除后可继续选
                                $.each($(".rule-item", _container).find(".actions"), function(i, _e){
                                    if (_ce[0] != this){
                                        $(_e).append('<option value="' +  o.id  + '">' + o.text + '</option>');
                                    }
                                })
                                canAdd();
                            })

                            //将已选的数据剔除
                            var selects = selectedActions(_container);
                            $.each(selects, function(i, _select){
                                $(_ce).find('option[value="' + _select.id  + '"]').remove();
                            })
                        }
                        ,afterAdd: function($box) {
                            //由于每种行为只能选择一次，故能增加的组数最多为行为数减去当前已选行为
                            canAdd();
                        }
                        ,beforeRemove : function($box){
                            //将已删的数据重新补回来
                            var _ce = $box.find(".actions");
                            var deleteds = $(_ce).select2("data");
                            $.each($(".rule-item", "#audience").find(".actions"), function(i, _e){
                                if (_ce[0] != this){
                                    $.each(deleteds, function(i, _delete){
                                        $(_e).append('<option value="' +  _delete.id  + '">' + _delete.text + '</option>');
                                    })
                                }
                            })

                        }
                        ,afterRemove:function($box){
                            canAdd();
                        }
                    });
                    cb.init();
                    _container.off('click', '.btn-plus').on('click', '.btn-plus', function() {
                        cb.add();
                    });

                    function selectedActions(_container){
                        var selects = [];
                        $.each($(".rule-item", _container).find(".actions"), function(i, _e) {
                            selects = selects.concat($(_e).select2("data"));
                        })
                        return selects;
                    }

                    function canAdd(){
                        var selectedNum = 0;
                        var actionsGroups = _container.find(".rule-item").find(".actions");
                        var _num;
                        $.each(actionsGroups, function(i, _actitons){
                            _num = $(_actitons).select2("data").length;
                            if (_num == 0){
                                _num += 1;
                            }
                            selectedNum += _num ;
                        })
                        if ((_this.actions.length - selectedNum) < 1){
                            _container.find('.btn-plus').addClass("hide");
                        } else {
                            _container.find('.btn-plus').removeClass("hide");
                        }
                    }
                }
            ,audience_init:function(){
                var _this = this;
                if (_this.audienceResultRequset){
                    _this.audienceResultRequset.abort();
                }

                //如果账号 未选择则无受众
                $("div.ndp-drop-wrapper[name=audience-drop]").off("ITEM_CLICK").empty().drop({
                    caret:"glyphicon-menu-right",
                    data:[],
                    name:"audience"//为了方便serialize 建议设置name 属性
                }).val({id : -1, text : I18N.getText("createAd","newAudience")});

                $(".customaudience").empty().select2({
                    data:[],
                    placeholder: I18N.getText('management', 'chooseCustomAudience'),
                    multiple: true,
                    allowClear: false,
                    width: '100%'
                })

                $("#audiencePople").empty();

                //受众处的商品系列
                $("div.ndp-drop-wrapper[name='audience-product-set-drop']").empty().drop({
                    caret:"glyphicon-menu-right",
                    data:adUtils.productSets,
                    name:"audience"//为了方便serialize 建议设置name 属性
                }).off("ITEM_CHANGE").on("ITEM_CHANGE", function(e){
                    console.log(e.originalEvent.data)
                    if (-1 != $('div.ndp-drop-wrapper[name="audience-drop"]').data("val")){
                        //如果是模板则重新生成用户定位
                        _this.previewEcSimpleUserAudience(e.originalEvent.data.val);
                    }
                }).val(adUtils.selectedProductSet)

                $('input[name="cross-selling"]').off("click").on("click", function(){
                    //改变了是否交叉销售 如果是模板则重新生成用户定位
                    var _audienceProductSetId;
                    if ($(this).prop("checked")){
                        $(".retarget-container").removeClass("hide");
                        _audienceProductSetId = $('div.ndp-drop-wrapper[name="audience-product-set-drop"]').data("val");
                    } else {
                        $(".retarget-container").addClass("hide");
                        _audienceProductSetId = adUtils.publishParamCache.productSetId;
                    }

                    if (-1 != $('div.ndp-drop-wrapper[name="audience-drop"]').data("val")){
                        //如果是模板则重新生成用户定位
                        _this.previewEcSimpleUserAudience(_audienceProductSetId);
                    }
                })


                var fbAccountId = $("div.ndp-drop-wrapper[name=account-drop]").data("val");
                if (-1 != fbAccountId){
                    //初始化 受众模板
                    http.do('/ec/audienceInit',{weFeedId:adUtils.publishParamCache.weFeedId,fbAccountId: adUtils.publishParamCache.fbAccountId},'GET').then(function(res) {
                        //后台有错。
                        if (res.flag == 'fail') {
                            Kit.alert2(res.errorMsg);
                            return;
                        }
                        _this.audienceTemplates = res.data.audience;
                        var appsData = [{id : -1, text : I18N.getText("createAd","newAudience")}];
                        var audience = res.data.audience;
                        $.each(audience, function (i, obj) {
                            //处理渲染的数据
                            obj.text = obj.name;
                            appsData.push(obj);
                        });

                        var customAudiences = [];
                        if (res.data.customAudiences){
                            customAudiences = res.data.customAudiences;
                        }
                        $.each(customAudiences, function(i, customAudience){
                            customAudience.text = customAudience.name;
                        });
                        _this.customAudiences = customAudiences;
                        adUtils.audienceCache = {};
                        _this.renderAudienceTemplates(appsData, appsData[0]);

                    });
                }
            }
            ,renderAudienceTemplates : function(_datas, _default){
                var _this = this;
                $("div.ndp-drop-wrapper[name=audience-drop]").empty().drop({
                    caret:"glyphicon-menu-right",
                    data:_datas,
                    name:"audience"//为了方便serialize 建议设置name 属性
                }).off("ITEM_CHANGE").on("ITEM_CHANGE",function(e){//下拉选择项点击事件
                    //返回的数据有
                    var _audienceId = e.originalEvent.data.val;
                    adUtils.publishParamCache.userAudienceId= _audienceId;

                    //生成用户定位 后台接口有问题
                    adUtils.audienceCache = {};
                    _this.user_localization();
                }).val(_default);

                adUtils.publishParamCache.userAudienceId= _default.id;

                //生成用户定位
                _this.user_localization();
            }
            ,user_localization:function(){
                var _this = this;
                $(".audience-result", "#audience").empty();
                var _audience = $('div.ndp-drop-wrapper[name="audience-drop"]').drop("data");
                _this.audience = _audience;
                if (_audience.id == -1){

                    //新受众
                    $(".new-audience-c").html(_.template($('#t-new-audience').text())());
                    $(".new-audience").show();
                    $("#audience").find(".btn-save-audience").addClass("disabled");
                    _this.renderAudience($("#audience"));
                    $(".audience-template").addClass("hide");
                } else {
                    $(".new-audience").hide();
                    //显示详情
                    var details = [];
                    var targetObj = JSON.parse(_audience.localTargeting);

                    //加入规则  如：  最近1至30天，加入购物车，但未购买
                    var ruleChildren = [];
                    $.each(targetObj.rules,function(i,obj){
                        var ruleTemplate = I18N.getText("createAd","recently") + obj.min + (obj.max== ""?"":"~" + obj.max) + I18N.getText("createAd","recentlyDay2");
                        var includeActions = [];
                        var excludeActions = [];
                        $.each(obj.actions,function(i,oo){
                            var show = "";
                            if(oo.id == "ViewContent"){
                                show = "Viewed";
                            }else if(oo.id=="AddToCart"){
                                show = "Added to cart";
                            }else if(oo.id=="Purchase"){
                                show = "Purchased";
                            }

                            if(oo.isClude == "1"){
                                includeActions.push(show);
                            }else{
                                excludeActions.push(show);
                            }
                        });
                        ruleTemplate += includeActions.join();
                        if (includeActions.length && excludeActions.length){
                            ruleTemplate += ";";
                        }
                        if (excludeActions.length){
                            ruleTemplate += I18N.getText("createAd","not") + excludeActions.join();
                        }
                        ruleChildren.push(ruleTemplate);
                    });
                    details.push({content:I18N.getText("createAd","productAudience") +":", children: ruleChildren});

                    //加入版位
                    var _pageType = targetObj.page_types.join().replace("mobilefeed",I18N.getText("createAd","mobileNewsFeed"))
                        .replace("mobileexternal",I18N.getText("createAd","mobileApplicationNet"))
                        .replace("desktopfeed",I18N.getText("createAd","desktopNewsFeed"))
                        .replace("rightcolumn",I18N.getText("createAd","desktopRightColumn"));
                    details.push({content:I18N.getText("createAd","pageType") +":", children: [_pageType]});

                    //自定义受众
                    var customAudiences = targetObj.customAudiences;
                    if (customAudiences && customAudiences.length){
                        var includeCAs = [];
                        var excludeCAs = [];
                        $.each(customAudiences, function(i, customAudience){
                            if (customAudience.isClude == "1"){
                                includeCAs.push(customAudience.name);
                            } else {
                                excludeCAs.push(customAudience.name);
                            }
                        });

                        if (includeCAs.length){
                            details.push({content:I18N.getText("createAd","customAudience")+":", children: [includeCAs.join()]});
                        }

                        if (excludeCAs.length){
                            details.push({content:I18N.getText("createAd","excludeCustomAudience")+":", children: [excludeCAs.join()]})
                        }
                    }

                    //地区
                    var containRegion =[],NotContainRegion = [];
                    $.each(targetObj.location.locations,function(i,obj){
                        if(obj.isClude == "1"){
                            containRegion.push(obj.name);
                        }else{
                            NotContainRegion.push(obj.name);
                        }
                    });
                    //加入地区
                    if (containRegion.length){
                        var locationDetail = {};
                        switch (Number(targetObj.location.locationType)){
                            case 1:
                                locationDetail.content = I18N.getText("createAd","peopleAllHere") + ": ";
                                break;
                            case 2:
                                locationDetail.content = I18N.getText("createAd","peopleLiveInHere") + ": ";
                                break;
                            case 3:
                                locationDetail.content = I18N.getText("createAd","peopleRecentlyHere") + ": ";
                                break;
                            case 4:
                                locationDetail.content = I18N.getText("createAd","peopleTravelingHere") + ": ";
                                break;
                            default:
                                break;
                        }
                        locationDetail.children = [containRegion.join()];
                        details.push(locationDetail);
                    }

                    //排除的地区
                    if (NotContainRegion.length){
                        details.push({content:I18N.getText("createAd","excludePlace") + ": ", children: [NotContainRegion.join()]})
                    }


                    //加入年龄
                    details.push({content:I18N.getText("createAd","age") + ": ", children: [targetObj.age.age_min + "-" + targetObj.age.age_max]})

                    //加入性别
                    if (targetObj.gender != "0"){
                        details.push({content:I18N.getText("createAd","gender") + ": ", children: [targetObj.gender == "1" ? I18N.getText("createAd","men") : I18N.getText("createAd","women")]})
                    }

                    $(".audience-template").find(".audience-detail-c>li").html(_.template($('#t-audience-detail').text())({details : details}));
                    $(".audience-template").removeClass("hide");

                    _this.previewEcSimpleUserAudience(adUtils.publishParamCache.productSetId);

                }
            },
            previewEcSimpleUserAudience : function(_productSetId){
                var _this = this;
                if (_this._previewRequest){
                    _this._previewRequest.abort();
                }

                var _previewParam = {
                    adAccountId:adUtils.publishParamCache.fbAccountId,
                    audienceId:adUtils.publishParamCache.userAudienceId,
                    productSetId:_productSetId
                }


                _this._previewRequest = http.work("/useraudiences/previewEcSimpleUserAudience",
                    _previewParam, 'POST');
                _this._previewRequest.then(function(result){
                    if(result.flag == "fail"){
                        Kit.alert(result.errorCode,result.msg);
                    }else{
                        //isComplete = false;
                        start = new Date();
                        setTimeout(function(){
                            _this.keepCalling(result.data.userAudienceCacheId, $(".audience-template"), adUtils.audienceCache);
                        },200)
                    }
                },function(err){});
            }
            ,keepCalling:function(cacheId, _container, _cache){
                var _this = this;
                var recall = arguments.callee;
                var body = {param:JSON.stringify({"userAudienceCacheId":cacheId})};
                if (_this.audienceResultRequset){
                    _this.audienceResultRequset.abort();
                }
                _this.audienceResultRequset = http.do("/useraudiences/searchPreviewSimpleUserAudienceResult",body);
                _this.audienceResultRequset.then(function(result){
                    window.existsPreviewUserAudience = new Date().getTime();//记录一个产生用户定位的时间标记,作用户定位新增的选项提
                    if(typeof(result)=="string") result = JSON.parse(result);
                    if(result.flag != "success") {
                        _this.useraudienceError(result.msg, _container, _cache);
                        return false;
                    }
                    var da = result.data;
                    if(!da.isComplete){
                        setTimeout(function(){_this.keepCalling(cacheId, _container, _cache)},400);
                    }else{
                        if(da.previewUserAudienceResults[0].people!=undefined){
                            var _html = I18N.getText("createAd","audienceSize")
                            + da.previewUserAudienceResults[0].people
                            + I18N.getText("createAd", "people");
                            _cache.isSuccess = true;
                            _cache.potentialUser = da.previewUserAudienceResults[0].people;
                            $(".audience-result", _container).removeClass("audiencePeopleError").addClass("audiencePeople").html(_html);
                            $(".btn-save-audience", _container).removeClass("disabled");
                            $(".btn-generate-audience", _container).removeClass("disabled");
                        } else {
                            var _exception = JSON.parse(da.previewUserAudienceResults[0].exception);
                            var _error = _exception;
                            if ( _exception.error){
                                if ( _exception.error.error_user_msg){
                                    _error =  _exception.error.error_user_msg;
                                } else if (_exception.error.message){
                                    _error =  _exception.error.message;
                                }
                            }
                            _this.useraudienceError(_error, _container, _cache);
                        }
                    }
                },function(){});
            }
            ,useraudienceError:function(_msg, _container, _cache){
                $(".btn-generate-audience", _container).removeClass("disabled");
                Kit.clearObject(_cache)

                _cache.isFail = true;
                _container.find(".audience-result").addClass("audiencePeopleError").html('<span>' + I18N.getText("createAd", "audienceException") + '</span> | <span class="ndp-bubble-wrapper" name="audience_exception"   style="cursor: pointer;">' + I18N.getText("createAd", "failDetail") + '<span>');
                $(".ndp-bubble-wrapper[name='audience_exception']", _container).bubble({
                    type:1,//气泡 包含尾部两个 确定，取消按钮,
                    placement:"right",
                    icon:'',
                    content:_msg,
                    showType : 'hover'
                });
            }
        }
        return Step1;
    });
